#ifndef __GLBITMAP_H__
#define __GLBITMAP_H__

#include "../common/glut.h"

struct GlBitmap
{
	unsigned char	*rawData;
	int				x, y;
	void			*dataBlock;
	void (*bitmapExit)(void*);

	/*===========================================================*/

	/*===========================================================*/

	GlBitmap(int width, int height, void *d = 0)
	{
		rawData = new unsigned char[width * height * 4];
		x = width;
		y = height;
		dataBlock = d;
	}

	~GlBitmap() 
	{
		delete [] rawData;
	}

	/*===========================================================*/

	/*===========================================================*/

	unsigned char* get_data() const
	{
		return rawData; 
	}

	long get_size () const
	{
		return x * y * 4; 
	}

	void display_and_exit( void(*e)(void*) = 0 )
	{
		GlBitmap** bitmap = get_bitmap_ptr();
		*bitmap = this;
		bitmapExit = e;

		// a bug in the Windows GLUT implementation prevents us from
		// passing zero arguments to glutInit()
		int c = 1;
		char* dummy = "";

		glutInit( &c, &dummy );
		glutInitDisplayMode( GLUT_SINGLE | GLUT_RGBA );
		glutInitWindowSize( x, y );
		glutCreateWindow( "image" );
		glutKeyboardFunc(Key);
		glutDisplayFunc(Draw);
		glutMainLoop();
	}

	/*===========================================================*/
	// static methods for glut
	/*===========================================================*/

	static GlBitmap** get_bitmap_ptr()
	{
		static GlBitmap *gBitmap;
		return &gBitmap;
	}

	static void Key(unsigned char key, int x, int y)
	{
		switch (key) 
		{
			case 27:
				GlBitmap*   bitmap = *(get_bitmap_ptr());
				if (bitmap->dataBlock != 0 && bitmap->bitmapExit != 0)
					bitmap->bitmapExit( bitmap->dataBlock );
				exit(0);
		}
	}

	static void Draw( void )
	{
		GlBitmap*   bitmap = *(get_bitmap_ptr());
		glClearColor( 0.0, 0.0, 0.0, 1.0 );
		glClear( GL_COLOR_BUFFER_BIT );
		glDrawPixels( bitmap->x, bitmap->y, GL_RGBA, GL_UNSIGNED_BYTE, bitmap->rawData );
		glFlush();
	}
};

#endif // __GLBITMAP_H__